package com.jin.crud.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jin.crud.bean.QueryDto;
import com.jin.crud.bean.SysRole;
import com.jin.crud.bean.SysRoleMenu;
import com.jin.crud.bean.SysUserRole;
import com.jin.crud.common.exception.ResultException;
import com.jin.crud.common.utils.StringUtils;
import com.jin.crud.dao.SysRoleMapper;
import com.jin.crud.dao.SysRoleMenuMapper;
import com.jin.crud.dao.SysUserRoleMapper;
import com.jin.crud.service.SysRoleService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


/**
 * <p>
 * 角色信息表 服务实现类
 * </p>
 *
 * @author yuxuejin
 * @since 2021-11-16
 */
@Service
public class SysRoleServiceImpl implements SysRoleService {

    @Autowired
    SysRoleMapper roleMapper;

    @Autowired
    SysUserRoleMapper userRoleMapper;

    @Autowired
    SysRoleMenuMapper roleMenuMapper;

    @Override
    public PageInfo<SysRole> getAllRolePage(QueryDto queryDto) {
        PageHelper.startPage(queryDto.getPageNum(), queryDto.getPageSize());
        List<SysRole> page = roleMapper.getByPage(queryDto);
        return new PageInfo<>(page);
    }

    @Override
    public List<SysRole> getAllRole() {
        return roleMapper.selectList(null);
    }

    @Override
    public List<String> selectRoleListByUserId(String userId) {
        return roleMapper.selectRoleListByUserId(userId);
    }

    @Override
    public SysRole getRole(String roleId) {
        return roleMapper.selectById(roleId);
    }

    @Override
    public void addRole(SysRole role) {
        if (this.checkRoleAllowed(role)) {
            throw new ResultException(2021101, "角色名称已存在");
        }
        String time = String.valueOf(System.currentTimeMillis());
        role.setCreateTime(time);
        role.setUpdateTime(time);
        role.setUpdateBy("刘一手");
        roleMapper.insert(role);
    }

    @Override
    public void updateRole(SysRole role) {
        if (this.checkRoleAllowed(role)) {
            throw new ResultException(2021102, "角色名称已存在");
        }
        String time = String.valueOf(System.currentTimeMillis());
        role.setUpdateTime(time);
        role.setUpdateBy("刘一手");
        roleMapper.updateRole(role);
        // 删除角色与菜单关联
        roleMenuMapper.deleteRoleMenuByRoleId(role.getRoleId());
        if (StringUtils.isNotEmpty(role.getMenuIds())) {
            insertRoleMenu(role);
        }
    }

    /**
     * 新增角色菜单信息
     *
     * @param role 角色对象
     */
    public void insertRoleMenu(SysRole role) {
        // 新增用户与角色管理
        List<SysRoleMenu> list = new ArrayList<>();
        for (String menuId : role.getMenuIds()) {
            SysRoleMenu rm = new SysRoleMenu();
            rm.setRoleId(role.getRoleId());
            rm.setMenuId(menuId);
            list.add(rm);
        }
        roleMenuMapper.batchRoleMenu(list);
    }

    @Override
    public void delRole(String roleId) {
        if (StringUtils.isEmpty(roleId)) {
            throw new ResultException(2021003, "未找到角色ID");
        }
        SysRole sysRole = new SysRole();
        sysRole.setRoleId(roleId);
        sysRole.setDelFlag("1");
        roleMapper.updateRole(sysRole);
    }

    @Override
    public void updateRoleStatus(String roleId, String status) {
        if (StringUtils.isEmpty(roleId)) {
            throw new ResultException(2021003, "未找到角色ID");
        }
        SysRole sysRole = new SysRole();
        sysRole.setRoleId(roleId);
        sysRole.setStatus(status);
        sysRole.setUpdateTime(String.valueOf(System.currentTimeMillis()));
        sysRole.setUpdateBy("刘一手");
        roleMapper.updateRole(sysRole);
    }

    @Override
    public void deleteAuthUser(SysUserRole userRole) {
        userRoleMapper.deleteUserRoleInfo(userRole);
    }

    @Override
    public void deleteAuthUsers(String roleId, String[] userIds) {
        userRoleMapper.deleteUserRoleInfos(roleId, userIds);
    }

    public boolean checkRoleAllowed(SysRole role) {
        String roleId = StringUtils.isBlank(role.getRoleId()) ? "id is empty" : role.getRoleId();
        SysRole sysRole = roleMapper.checkRoleNameUnique(role.getRoleName());
        return ObjectUtils.isNotEmpty(sysRole) && !roleId.equals(sysRole.getRoleId());
    }

    @Override
    public void insertAuthUsers(String roleId, String[] userIds) {
        // 新增用户与角色管理
        List<SysUserRole> list = new ArrayList<SysUserRole>();
        for (String userId : userIds) {
            SysUserRole ur = new SysUserRole();
            ur.setUserId(userId);
            ur.setRoleId(roleId);
            list.add(ur);
        }
        userRoleMapper.batchUserRole(list);
    }

    @Override
    public Set<String> selectRolePermissionByUserId(String userId) {
        List<SysRole> perms = roleMapper.selectRolePermissionByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (SysRole perm : perms) {
            if (StringUtils.isNotNull(perm)) {
                permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
                System.out.println(permsSet);
            }
        }
        return permsSet;
    }
}
